package org.sgx.gapigui.client.ui.actions.urlshortener;

import org.sgx.gapigui.client.Main;
import org.sgx.gapigui.client.control.ControllerCallback;
import org.sgx.gapigui.client.ui.editableModels.urlShortener.Url;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

public class UrlShortener extends Composite {

	private static UrlShortenerUiBinder uiBinder = GWT.create(UrlShortenerUiBinder.class);

	interface UrlShortenerUiBinder extends UiBinder<Widget, UrlShortener> {
	}

	@UiField InputElement shortenInput, originalInput; 
	@UiField Button shortenButton, getOriginalButton; 
    
	public UrlShortener() {
		initWidget(uiBinder.createAndBindUi(this));
		shortenButton.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				doShorten();
			}
		}); 		
		getOriginalButton.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				doGetOriginal();
			}
		});
		shortenInput.setValue("http://www.google.com"); 
		originalInput.setValue("http://goo.gl/fbsS"); 
	}

	protected void doGetOriginal() {
		Main.controller().urlShortenerGetOriginal(originalInput.getValue(), new ControllerCallback<Url>() {			
			@Override
			public void call(Url result) {
				Window.alert("The original url is: "+result.getLongUrl()); 
			}
		}); 
	}

	protected void doShorten() {
		Main.controller().urlShortenerInsert(shortenInput.getValue(), new ControllerCallback<Url>() {			
			@Override
			public void call(Url result) {
				Window.alert("Shortened UrlResourceBean is: "+result.getId()); 
			}
		}); 
	}

}
